const AiPerson = require("../models/AiPerson");
const fs = require("fs");
const path = require("path");

// 读取character_profile.json文件
const getCharacterProfiles = () => {
  try {
    const profilesPath = path.join(__dirname, "../../character_profile.json");
    return JSON.parse(fs.readFileSync(profilesPath, "utf8"));
  } catch (error) {
    console.error("读取角色档案文件失败:", error);
    return [];
  }
};

// 获取默认角色档案模板
const getDefaultCharacterProfile = (id) => {
  const profiles = getCharacterProfiles();
  // 根据ID查找匹配的档案，如果没有则使用第一个作为模板
  const template =
    profiles.find((profile) => profile.id === id) || profiles[0] || {};

  // 返回克隆的模板，更新ID
  const newProfile = { ...template };
  if (newProfile) {
    newProfile.id = id;
  }
  return newProfile;
};

/**
 * 获取AI人物列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * 
 * 请求参数：
 * - information: boolean, 默认true
 *   - true: 只返回character_profiles中的数据(会展开character_profiles对象，并包含id字段)
 *   - false: 只返回指定字段(id, information, avatar, image, likes, comments, is_premium, description, images, videos, type, country)
 * - language: string, 默认"CN"
 *   - "JP": 只返回country为"JP"的记录
 *   - "EN": 只返回country为"EN"的记录
 *   - 其他值: 匹配对应的country字段
 *   - "CN": 不进行country过滤
 * - type: string, 可选，按type字段过滤
 * - page: number, 页码，默认1
 * - pageSize: number, 每页数量，默认10
 */
exports.getList = async (req, res) => {
  const { information = true, type, language = "CN" } = req.body;

  try {
    // 获取分页参数，设置默认值
    const page = parseInt(req.body.page) || 1;
    const pageSize = parseInt(req.body.pageSize) || 10;
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const where = {};
    if (type) {
      where.type = type;
    }
    
    // 根据language参数过滤country字段
    if (language && language !== "CN") {
      where.country = language;
    }
    // 只返回上架（status为true）的数据
    where.status = true;

    // 查询总数
    const total = await AiPerson.count({ where });

    if (information === true) {
      // 只返回character_profiles字段的数据
      const aiPersons = await AiPerson.findAll({
        attributes: ["id", "character_profiles"],
        where,
        offset,
        limit: pageSize,
        order: [["id", "ASC"]],
      });

      const list = aiPersons.map((person) => {
        return {
          id: person.id,
          ...person.character_profiles
        };
      });

      return res.status(200).json({
        success: true,
        data: {
          list,
          pagination: {
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
          },
        },
      });
    } else {
      // 只返回指定字段：id, information, avatar, likes, comments, is_premium, description, images, videos, type, country
      const aiPersons = await AiPerson.findAll({
        attributes: [
          "id",
          "information",
          "avatar",
          "image",
          "likes",
          "comments",
          "is_premium",
          "description",
          "images",
          "videos",
          "type",
          "country"
        ],
        where,
        order: [["id", "ASC"]],
        offset,
        limit: pageSize,
      });

      const list = aiPersons.map((person) => {
        return person.toJSON();
      });

      return res.status(200).json({
        success: true,
        data: {
          list,
          pagination: {
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
          },
        },
      });
    }
  } catch (error) {
    console.error("获取AI人物列表错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error:
        process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 创建新的AI人物
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * 
 * 请求数据示例：
 * {
 *   "information": {
 *     "name": "小雪",
 *     "age": 22,
 *     "gender": "女",
 *     "occupation": "学生"
 *   },
 *   "avatar": "https://example.com/avatar.jpg",
 *   "image": "https://example.com/image.jpg",
 *   "likes": "1234",
 *   "comments": "567",
 *   "is_premium": false,
 *   "description": "一个活泼可爱的女孩，喜欢音乐和绘画。",
 *   "images": [
 *     "https://example.com/image1.jpg",
 *     "https://example.com/image2.jpg"
 *   ],
 *   "videos": [
 *     "https://example.com/video1.mp4"
 *   ],
 *   "character_profiles": {
 *     "personality": "开朗、友善",
 *     "hobbies": ["音乐", "绘画", "阅读"],
 *     "background": "来自小城市的艺术学院学生",
 *     "promptWord": "你是一个活泼可爱的艺术学院学生小雪，喜欢音乐和绘画，性格开朗友善。",
 *     "voice_settings": {
 *       "vol": "1",
 *       "pitch": "2",
 *       "speed": "1",
 *       "voice_id": "",
 *       "timber_weights": [
 *         {"weight": 50, "voice_id": "abcd"},
 *         {"weight": 50, "voice_id": "wert"}
 *       ]
 *     },
 *     "aiPersion_id": "自动生成，与主键id一致"
 *   },
 *   "type": "学生",
 *   "country": "JP"
 * }
 */
exports.create = async (req, res) => {
  try {
    const {
      information,
      avatar,
      image,
      likes,
      comments,
      is_premium = false,
      description,
      images,
      videos,
      character_profiles,
      type,
      country = 'JP'
    } = req.body;

    // 验证必填字段
    if (!avatar || !image || !likes || !comments || !description || !images || !type) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：avatar, image, likes, comments, description, images, type"
      });
    }

    // 构建创建数据
    const personData = {
      information,
      avatar,
      image,
      likes,
      comments,
      is_premium,
      description,
      images,
      videos,
      character_profiles,
      type,
      country
    };

    // 创建AI人物
    const aiPerson = await AiPerson.create(personData);

    // 如果提供了character_profiles，需要在其中添加aiPersion_id字段
    if (character_profiles && Object.keys(character_profiles).length > 0) {
      const updatedCharacterProfiles = {
        ...character_profiles,
        aiPersion_id: aiPerson.id
      };
      
      // 更新character_profiles字段
      await aiPerson.update({ 
        character_profiles: updatedCharacterProfiles 
      });
      
      // 重新获取更新后的数据
      const updatedAiPerson = await AiPerson.findByPk(aiPerson.id);
      
      return res.status(201).json({
        success: true,
        message: "AI人物创建成功",
        data: updatedAiPerson,
      });
    }

    return res.status(201).json({
      success: true,
      message: "AI人物创建成功",
      data: aiPerson,
    });
  } catch (error) {
    console.error("创建AI人物错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 更新AI人物信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * 
 * 支持多语言更新，根据 information.language 字段确定语言版本
 * - Japanese: 更新日语版本字段
 * - English: 更新英语版本字段  
 * - 其他: 更新默认字段
 */
exports.update = async (req, res) => {
  try {
    const { id, information, language } = req.body;

    // 验证请求
    if (!id) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：id",
      });
    }

    const aiPerson = await AiPerson.findByPk(id);
    if (!aiPerson) {
      return res.status(404).json({
        success: false,
        message: "AI人物不存在",
      });
    }

    // 从请求中获取语言信息，优先使用 information.language，然后是 language 参数
    const targetLanguage = information?.language || language || "Chinese";
    
    // 构建更新数据
    const updateData = { ...req.body };
    
    // 根据语言类型处理多语言字段
    if (targetLanguage === "Japanese" || targetLanguage === "JP") {
      // 如果是日语，存储到对应的多语言字段（如果存在的话）
      // 由于当前模型没有多语言字段，我们可以在 character_profiles 中存储多语言数据
      if (updateData.character_profiles) {
        const currentProfiles = aiPerson.character_profiles || {};
        updateData.character_profiles = {
          ...currentProfiles,
          ...updateData.character_profiles,
          language: targetLanguage,
          aiPersion_id: aiPerson.id
        };
      }
    } else if (targetLanguage === "English" || targetLanguage === "EN") {
      // 英语版本处理
      if (updateData.character_profiles) {
        const currentProfiles = aiPerson.character_profiles || {};
        updateData.character_profiles = {
          ...currentProfiles,
          ...updateData.character_profiles,
          language: targetLanguage,
          aiPersion_id: aiPerson.id
        };
      }
    } else {
      // 默认中文版本或其他语言
      if (updateData.character_profiles) {
        const currentProfiles = aiPerson.character_profiles || {};
        updateData.character_profiles = {
          ...currentProfiles,
          ...updateData.character_profiles,
          language: targetLanguage,
          aiPersion_id: aiPerson.id
        };
      }
    }

    // 确保 character_profiles 中包含 aiPersion_id
    if (updateData.character_profiles) {
      updateData.character_profiles.aiPersion_id = aiPerson.id;
    }

    // 执行更新
    await aiPerson.update(updateData);

    // 刷新当前实例以获取最新数据，避免额外查询
    await aiPerson.reload();

    return res.status(200).json({
      success: true,
      message: `AI人物更新成功 (${targetLanguage})`,
      data: aiPerson,
    });
  } catch (error) {
    console.error("更新AI人物错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 删除AI人物
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.delete = async (req, res) => {
  try {
    const { id } = req.body;

    const aiPerson = await AiPerson.findByPk(id);
    if (!aiPerson) {
      return res.status(404).json({
        success: false,
        message: "AI人物不存在",
      });
    }

    await aiPerson.destroy();

    return res.status(200).json({
      success: true,
      message: "AI人物删除成功",
    });
  } catch (error) {
    console.error("删除AI人物错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 获取AI人物详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getDetail = async (req, res) => {
  try {
    const { id, language = "CN" } = req.query;

    // 验证请求
    if (!id) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：id",
      });
    }

    // 查找AI人物
    const aiPerson = await AiPerson.findByPk(id);
    if (!aiPerson) {
      return res.status(404).json({
        success: false,
        message: "AI人物不存在",
      });
    }

    // 获取完整的AI人物数据
    const data = aiPerson.toJSON();
    
    // 确保返回description字段
    return res.status(200).json({
      success: true,
      data: {
        ...data,
        description: aiPerson.description // 确保description字段被正确返回
      },
    });
  } catch (error) {
    console.error("获取AI人物详情错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 获取AI人物角色档案
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getCharacterProfile = async (req, res) => {
  try {
    const { id } = req.query;
    console.log("传递的人设id", id);

    // 验证请求
    if (!id) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：id",
      });
    }

    // 查找AI人物
    const aiPerson = await AiPerson.findByPk(id);
    if (!aiPerson) {
      return res.status(404).json({
        success: false,
        message: "AI人物不存在",
      });
    }

    // 直接返回character_profiles字段的数据
    const characterProfiles = aiPerson.character_profiles || {};

    return res.status(200).json({
      success: true,
      data: characterProfiles,
    });
  } catch (error) {
    console.error("获取AI人物角色档案错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 更新AI人物角色档案
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateCharacterProfile = async (req, res) => {
  try {
    const { id } = req.body;

    // 验证请求
    if (!id) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：id",
      });
    }

    // 查找AI人物
    const aiPerson = await AiPerson.findByPk(id);
    if (!aiPerson) {
      return res.status(404).json({
        success: false,
        message: "AI人物不存在",
      });
    }

    // 获取当前的角色档案
    const currentProfile = aiPerson.character_profile || {};

    // 合并更新的字段（除了id外其他字段都是非必传的）
    const updatedProfile = {
      ...currentProfile,
      ...req.body.character_profile,
      id: aiPerson.id, // 确保ID保持一致
    };

    // 更新角色档案
    await aiPerson.update({ character_profile: updatedProfile });

    return res.status(200).json({
      success: true,
      message: "AI人物角色档案更新成功",
      data: { character_profile: updatedProfile },
    });
  } catch (error) {
    console.error("更新AI人物角色档案错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 获取AI人物详情（简化版）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAiPersionDetail = async (req, res) => {
  try {
    const { id, language = "CN" } = req.body;

    // 验证请求
    if (!id) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：id",
      });
    }

    // 查找AI人物
    const aiPerson = await AiPerson.findByPk(id);
    if (!aiPerson) {
      return res.status(404).json({
        success: false,
        message: "AI人物不存在",
      });
    }

    // 获取角色配置文件数据
    const characterProfiles = aiPerson.character_profiles || {};
    
    // 获取基本信息
    let characterProfile = {};
    if (language === "EN" && characterProfiles.language === "English") {
      characterProfile = characterProfiles;
    } else if (language === "JP" && characterProfiles.language === "Japanese") {
      characterProfile = characterProfiles;
    } else {
      characterProfile = characterProfiles;
    }

    // 从character_profiles中提取需要的字段
    const age = characterProfile?.basic_info?.age;
    const gender = characterProfile?.basic_info?.gender;
    const zodiac = characterProfile?.basic_info?.zodiac;
    const birthday = characterProfile?.basic_info?.birthday;
    const jobs = characterProfile?.occupation?.jobs;
    
    // 获取名称 - 优先从character_profiles获取name字段
    const username = characterProfile?.name || 
                    (aiPerson.information ? aiPerson.information.name : null);

    // 构建返回数据，只包含指定字段
    const responseData = {
      id: aiPerson.id,
      image: aiPerson.image,
      avatar: aiPerson.avatar,
      status: aiPerson.status, // 确保status字段被返回
      username,
      isPremium: aiPerson.is_premium, // 修正字段名称
      images: aiPerson.images,
      videos: aiPerson.videos,
      description: aiPerson.description,
      information: aiPerson.information || {},
      age,
      gender,
      zodiac,
      birthday,
      jobs,
    };

    return res.status(200).json({
      success: true,
      data: responseData,
    });
  } catch (error) {
    console.error("获取AI人物详情错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};
